from crawler_baike import url_manager, html_dl, html_parser, html_output


class SpiderMain(object):
    def __init__(selfs):
        selfs.urls = url_manager.UrlManager()
        selfs.dl = html_dl.HtmlDownloader()
        selfs.parser = html_parser.HtmlParser()
        selfs.output = html_output.HtmlOutput()

    def craw(selfs, root_url):
        count = 1
        selfs.urls.add_new_url(root_url)

        while selfs.urls.has_new_url():
            try:
                new_url = selfs.urls.get_new_url()
                print('craw 0.... %d: %s' % (count, new_url))
                html_content = selfs.dl.download(new_url)
                print('craw 1... html_content: %s' % html_content)
                new_urls, new_data = selfs.parser.parse(new_url, html_content)
                print('craw 2...')
                selfs.urls.add_new_urls(new_urls)
                print('craw 3...')
                selfs.output.collect_data(new_data)
                print('craw 4...')

                if count > 100:
                    break
                count += 1
            except Exception as e:
                print('craw failed: %s' % e)

        selfs.output.output_html()


# if __name__ == '__main__' 就相当于是 Python 模拟的程序入口。Python 本身并没有规定这么写，这只是一种编码习惯。由于模块之间相互引用，
# 不同模块可能都有这样的定义，而入口程序只能有一个。到底哪个入口程序被选中，这取决于 __name__ 的值
# __name__ 是内置变量，用于表示当前模块的名字，同时还能反映一个包的结构
# 如果模块是被直接运行的，则代码块被运行，如果模块是被导入的，则代码块不被运行
if __name__ == '__main__':
    root_url = "https://baike.baidu.com/item/Python/407313"
    obj_spider = SpiderMain()
    obj_spider.craw(root_url)
